/**
 * @Project TMHSC
 * @Author Tran Manh Hung
 * @Email: hungtmit@gmail.com | tmh@xwebgate.com
 * @Copyright © 2011 TMH. All rights reserved
 * @Createdate Feb 9, 2011
 * @Createtime 11:45:51 AM
 */

package com.tmh.study.fMVW
{
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	import it.gotoandplay.smartfoxserver.SFSEvent;
	import it.gotoandplay.smartfoxserver.SmartFoxClient;

	public class Ch03_01 extends MovieClip
	{
		private var _sfs:SmartFoxClient;

		private var _drawing:Boolean = false;

		public function Ch03_01()
		{
			_sfs = new SmartFoxClient(true);

			_sfs.addEventListener(SFSEvent.onConnection, onConnection);
			_sfs.addEventListener(SFSEvent.onRoomListUpdate, onRoomListUpdate);
			_sfs.addEventListener(SFSEvent.onPublicMessage, onPublicMessage);

			_sfs.connect("127.0.0.1", 9339);

			stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, drawing);
			stage.addEventListener(MouseEvent.MOUSE_UP, stopDraw);
		}

		private function onConnection(e:SFSEvent):void
		{
			var ok:Boolean = e.params.success;

			if (ok)
			{
				_sfs.login("simpleChat", "", "");
			}
		}

		private function onRoomListUpdate(e:SFSEvent):void
		{
			_sfs.autoJoin();
		}

		private function onPublicMessage(e:SFSEvent):void
		{
			/* Get the message from the onPublicMessage Event*/
			var message:String = e.params.message;

			// Split the Array into three parts by the comma ','
			var splitArray:Array = message.split(',');

			/* The starting indicates that the coordinatation
			* is a starting point or drawing point */
			var starting:Number = Number(splitArray[0]);

			/* The coordination of the drawing point */
			var pointX:Number = Number(splitArray[1]);
			var pointY:Number = Number(splitArray[2]);

			/* Move the starting point if it is the first point
			of the line*/
			if (starting == 1)
			{
				this.graphics.moveTo(pointX, pointY);
			}
			else
			{
				/* Draw the line accroding to the received
				cooredination */
				this.graphics.lineStyle(5, 0xcc0000);
				this.graphics.lineTo(pointX, pointY);
			}
		}

		private function startDrawing(e:MouseEvent):void
		{
			/* Send a public message with coordination as message
			text */
			_sfs.sendPublicMessage('1,' + mouseX + ',' + mouseY);
			_drawing = true;
		}

		private function drawing(e:MouseEvent):void
		{
			if (_drawing)
			{
				_sfs.sendPublicMessage('0,' + mouseX + ',' + mouseY);
			}
		}

		private function stopDraw(e:MouseEvent):void
		{
			_drawing = false;
		}
	}
}